package com.ssu.judea.palmssu.model;

import java.awt.List;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;

import statics.PalmVars;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ssu.judea.palmssu.vo.GraphItem;
import com.ssu.judea.palmssu.vo.Member;
import com.ssu.judea.palmssu.vo.MemberItem;
import com.ssu.judea.palmssu.vo.MemberValue;
import com.ssu.judea.palmssu.vo.StudyInfo;

import comm.util.RequestManager;
import comm.util.PalmHashMap;
import comm.util.SqlMapLoader;
import comm.util.TwitterAPI;

public class AndroidDAO {
	private TwitterAPI twit;
	private Logger logger = Logger.getLogger(AndroidDAO.class);
	private SqlMapClient sqlMapper;
	public AndroidDAO() {
		if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
	}
	
	 

	public void toAuthpage(HttpServletRequest request,HttpServletResponse response){
		TwitterAPI twit = new TwitterAPI();
		twit.toAuthMobilePage(request, response);
	}
	public void toTwitterPage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		PalmHashMap hm = RequestManager.getRequest(request);
		if(hm.get("URL")!=null){
			request.getSession().setAttribute("TWITTER_TOKEN_SECRET", hm.get("SECRET").toString());
			response.sendRedirect(hm.get("URL").toString());
		}
	}
	
	
	public Member authorizeFromMobile(HttpServletRequest request, HttpServletResponse response) throws ParserConfigurationException, IOException, SQLException{
		if(twit==null)twit = new TwitterAPI();
		return twit.regMemberFromMobile(request, response);
		
	}
	
	public Member getMemberBySeq(String seq){
		Member mem = null;
		try {
			if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
			mem = (Member) sqlMapper.queryForObject("member.getMemberBySeq",seq);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	
	public Member getMemberById(String id){
		Member mem = null;
		try {
			if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
			mem = (Member) sqlMapper.queryForObject("member.getMemberById",id);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	
	public Member getMemberByNumber(String num){
		Member mem = null;
		try {
			if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
			mem = (Member) sqlMapper.queryForObject("member.getMemberByNumber",num);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	
	public Member getMemberBySession(String session){
		Member mem = null;
		try {
			if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
			mem = (Member) sqlMapper.queryForObject("member.getMemberBySession",session);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	
	public String doWrite(String text,String room, String seat, boolean share,String session){
		logger.debug("=====doWrite in AndroidDAO 넘어온 내용");
		logger.debug(text);
		String result = PalmVars.FAIL;
		
		
		
		Member mem = null;
		try {
			if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
			mem = (Member) sqlMapper.queryForObject("member.getMemberBySession",session);
		} catch (SQLException e) {
			logger.debug("getMemberBySession에러"+e.getMessage());
		}
		
		if(share){
			//트윗 포스팅 처리
			if(twit==null)twit = new TwitterAPI();
			
			if(mem!=null)
				result = twit.writeTwit(mem.getTwitterpasskey(), text);
		}
		
		int insertedStudySeq = 0;
		//팜쓔 Stduy Table에 저장
		if(mem!=null){
			StudyInfo study = new StudyInfo();
			study.setMemberseq(mem.getMemberseq());
			study.setRoom(room);
			study.setSeat(seat);
			study.setComment(text);
			
			try {
				if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
				insertedStudySeq = Integer.parseInt(sqlMapper.insert("study.insertStudy", study).toString());
				if(insertedStudySeq>0){
					result = String.valueOf(insertedStudySeq);
					study.setSeq(insertedStudySeq);
				}
			} catch (SQLException e) {
				result = PalmVars.FAIL;
			}
			
			 
		}
		
		logger.debug("Twitter포스팅 결과"+result+"/PalmSSU포스팅 결과"+insertedStudySeq);
		
		return result;
	}
	
	public String doWriteMention(String text,String passkey){
		logger.debug("=====doWrite in AndroidDAO 넘어온 내용");
		logger.debug(text);
		String result = PalmVars.FAIL;
		
		//트윗 포스팅 처리
		if(twit==null)twit = new TwitterAPI();
		
		if(passkey.length()>0)
			result = twit.writeTwit(passkey, text);
		
		logger.debug("Twitter포스팅 결과"+result);
		
		return result;
	}
	
	public MemberValue getMemberValueBySeq(String memberseq){
		MemberValue value = new MemberValue();
		value.setMemberseq(Integer.parseInt(memberseq));
		try {
			int studyCount = Integer.parseInt(sqlMapper.queryForObject("study.getMemberStudyCount",memberseq).toString());
			value.setStudycount(studyCount);
			
			PalmHashMap roomHm = (PalmHashMap)sqlMapper.queryForObject("study.getMemberPrimaryRoom",memberseq);
			value.setPrimaryroom(Integer.parseInt(roomHm.get("STUDY_ROOM").toString()));
			PalmHashMap seatHm = (PalmHashMap)sqlMapper.queryForObject("study.getMemberPrimarySeat",memberseq);
			value.setPrimaryseat(Integer.parseInt(seatHm.get("STUDY_SEAT").toString()));
		} catch (SQLException e) {
			return value;
		}
		return value;
	}
	
	public int getMatchingRate(MemberValue clientValue,String targetSeq){
		//입력받은 두회원 간 매칭률
		//항목을 세분화 하고 Complex 한 알고리즘 설계 요함.
		int result = 0;
		
		MemberValue targetValue = getMemberValueBySeq(targetSeq);
		
		int count = 33;
		int room  = 33;
		int seat  = 33;
		
		if(Math.abs(clientValue.getStudycount()-targetValue.getStudycount())>32)count = 0;
		else count -= Math.abs(clientValue.getStudycount()-targetValue.getStudycount());
		
		if(Math.abs(clientValue.getPrimaryroom()-targetValue.getPrimaryroom())>32)room = 0;
		else room -= Math.abs(clientValue.getPrimaryroom()-targetValue.getPrimaryroom());
		
		if(Math.abs(clientValue.getPrimaryseat()-targetValue.getPrimaryseat())>32)seat = 0;
		else seat -= Math.abs(clientValue.getPrimaryseat()-targetValue.getPrimaryseat());
		
		result = count+room+seat;
		
		
		return result;
	}
	
	public int getMatchingRate(String clientSeq,String targetSeq){
		//입력받은 두회원 간 매칭률
		//항목을 세분화 하고 Complex 한 알고리즘 설계 요함.
		int result = 0;
		
		MemberValue clientValue = getMemberValueBySeq(clientSeq);
		MemberValue targetValue = getMemberValueBySeq(targetSeq);
		
		int count = 33;
		int room  = 33;
		int seat  = 33;
		
		if(Math.abs(clientValue.getStudycount()-targetValue.getStudycount())>32)count = 0;
		else count -= Math.abs(clientValue.getStudycount()-targetValue.getStudycount());
		
		if(Math.abs(clientValue.getPrimaryroom()-targetValue.getPrimaryroom())>32)room = 0;
		else room -= Math.abs(clientValue.getPrimaryroom()-targetValue.getPrimaryroom());
		
		if(Math.abs(clientValue.getPrimaryseat()-targetValue.getPrimaryseat())>32)seat = 0;
		else seat -= Math.abs(clientValue.getPrimaryseat()-targetValue.getPrimaryseat());
		
		result = count+room+seat;
		
		logger.debug("CURRENT MATCHING RATE :"+result);
		return result;
	}
	
	public ArrayList<MemberItem> getRecentList(String memberseq) {
		//parameter로 들어온 회원번호 외에 최근 리스트 출력(요청자는 제외한 결과
		ArrayList<MemberItem> list = null;
		
		if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
		
		try {
			list = (ArrayList<MemberItem>) sqlMapper.queryForList("study.getRecentList",memberseq);
			for(int i = 0; i<list.size();i++){
				MemberItem curItem = list.get(i);
				curItem.setMatchingrate(getMatchingRate(memberseq,curItem.getMemberseq()));
				list.set(i, curItem);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			return new ArrayList<MemberItem>();
		}
		logger.debug("get RecentList Result"+list.size());
		return list;
	}
	
	public ArrayList<MemberItem> getMatchingList(String memberseq) {
		//parameter로 들어온 회원번호 과 매칭이 되는 리스트 출력(요청자는 제외한 결과
		ArrayList<MemberItem> list = null;
		
		if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
		
		try {
			list = (ArrayList<MemberItem>) sqlMapper.queryForList("study.getRecentList",memberseq);
			for(int i = 0; i<list.size();i++){
				MemberItem curItem = list.get(i);
				curItem.setMatchingrate(getMatchingRate(memberseq,curItem.getMemberseq()));
				list.set(i, curItem);
			}
		} catch (SQLException e) {
			return new ArrayList<MemberItem>();
		}
		
		for(int i = 0; i<list.size()-1;i++){
			for(int j = i+1; j<list.size();j++){
				if(list.get(i).getMatchingrate()<list.get(j).getMatchingrate()){
					MemberItem curItem = list.get(j);
					list.set(j, list.get(i));
					list.set(i, curItem);
				}
			}
		}
		
		
		logger.debug("getMatchingList Result"+list.size());
		return list;
	}
	
	public ArrayList<MemberItem> getFollowersList(String memberseq) {
		//parameter로 들어온 회원의 follower들의 리스트 출력(요청자는 제외한 결과
		ArrayList<MemberItem> list = null;
		
		
		if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
		
		Member mem = getMemberBySeq(memberseq);
		
		String passkey = mem.getTwitterpasskey();
		
		//트윗 follow 처리
		if(twit==null)twit = new TwitterAPI();
		ArrayList<Integer> followersIds = null;
		if(passkey.length()>0)
			followersIds = twit.getMyFollowersList(passkey);
		
		if(followersIds!=null && followersIds.size()>0){
			list = new ArrayList<MemberItem>();
			for(int i = 0; i<followersIds.size();i++){
				
				try {
					MemberItem currentItem = new MemberItem();
					currentItem = (MemberItem)sqlMapper.queryForObject("study.getRecentMemberItemByNumber",String.valueOf(followersIds.get(i)));
					if(currentItem!=null)list.add(currentItem);
					
				} catch (SQLException e) {}
				
			}
			
			for(int i = 0; i<list.size();i++){
				MemberItem curItem = list.get(i);
				curItem.setMatchingrate(getMatchingRate(memberseq,curItem.getMemberseq()));
				list.set(i, curItem);
			}
			
			logger.debug("getFollowersList Result"+list.size());
		}
		return list;
	}
	
	public String doFollow(String targetId,String passkey){
		String result = PalmVars.FAIL;
		
		//트윗 follow 처리
		if(twit==null)twit = new TwitterAPI();
		
		if(passkey.length()>0)
			result = twit.follow(passkey, targetId);
		
		logger.debug("Twitter Follow 결과"+result);
		
		return result;
	}



	public ArrayList<GraphItem> getStudyTimeLine(String curClientSeq, String targetDate) {
		ArrayList<GraphItem> result = new ArrayList<GraphItem>();
		
		logger.debug("들어온 targetDate "+targetDate+"seq:"+curClientSeq);
		
		
		
		int[] dates = {-2,-1,0,1,2};
		for(int i = 0;i<dates.length;i++){
			PalmHashMap argHm = new PalmHashMap();
			argHm.put("member_seq", curClientSeq);
			argHm.put("date", targetDate);
			argHm.put("gap", dates[i]);
			
			ArrayList<PalmHashMap> arr;
			try {
				arr = (ArrayList<PalmHashMap>)sqlMapper.queryForList("study.getMembersStudyByDate",argHm);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				arr = null;
			}
			
			if(arr!=null&&arr.size()>0){
				GraphItem curItem = new GraphItem();
				float[] starttime  = new float[arr.size()];
				float[] endtime  = new float[arr.size()];
				
				int j = 0;
				for(PalmHashMap temp : arr){
					
					if(temp.get("STARTTIME")!=null){
						starttime[j] = Float.parseFloat(temp.get("STARTTIME").toString());
						if(temp.get("ENDTIME")!=null){
							endtime[j] = Float.parseFloat(temp.get("ENDTIME").toString());
						}else{
							endtime[j] = Float.parseFloat(temp.get("CONVERTENDTIME").toString());
						}
					}
					j++;
					
				}
				curItem.setStarttime(starttime);
				curItem.setEndtime(endtime);
				curItem.setMemberseq(Integer.parseInt(curClientSeq));
				result.add(curItem);
			}else{
				GraphItem curItem = new GraphItem();
				curItem.setMemberseq(Integer.parseInt(curClientSeq));
				result.add(curItem);
			}
			
		}
		return result;
	}



	public int updateEndStudyTime(String memberseq, String studyseq) {
		int result = 0;
		PalmHashMap argHm = new PalmHashMap();
		argHm.put("MEMBER_SEQ", memberseq);
		argHm.put("STUDY_SEQ",studyseq);
		try {
			result = sqlMapper.update("study.updateEndStudyTime",argHm);
		} catch (SQLException e) {
			return 0;
		}
		return result;
	}



	public ArrayList<Member> getFollowersInfo(String curClientSeq) {
		ArrayList<Member> list = null;
		
		
		if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
		
		Member mem = getMemberBySeq(curClientSeq);
		
		String passkey = mem.getTwitterpasskey();
		
		//트윗 follow 처리
		if(twit==null)twit = new TwitterAPI();
		ArrayList<Integer> followersIds = null;
		if(passkey.length()>0)
			followersIds = twit.getMyFollowersList(passkey);
		
		if(followersIds!=null && followersIds.size()>0){
			list = new ArrayList<Member>();
			for(int i = 0; i<followersIds.size();i++){
				Member currentItem = getMemberByNumber(followersIds.get(i).toString());
				
				if(currentItem!=null)list.add(currentItem);
			}
			
			logger.debug("getFollowersInfo Result"+list.size());
		}
		return list;
	}

}
